Hello World
GeeksforGeeks - A computer science portal for geeks
Enter your age:
Input : 18
Your age is: 18
An error occured
An error occured
Hello World!
A preprocessor directive is a statement which gets processed by the C++ preprocessor before compilation.
#include <file_name>where file_name is the name of file to be included. The '<' and '>' brackets tells the compiler to look for the file in standard directory.
#include "filename"
Perimeter of Circle: 31.4159
Area of Circle: 78.5398
#define f(l,r) for (int i = l; i < r; i++)
#define ll long long
#define ull unsigned long long
#define abs(x) (x < 0 ? (-x) : x)
Variables Contd.
Scope of Variables
Compilation Error:
prog.cpp: In function 'int main()':
prog.cpp:14:37: error: 'age' was not declared in this scope
cout << "Outside Function: " << age << endl;
^
Access inside func: 10
Access inside main: 10
Value of global x is 5
Value of local x is 10
Data-type Modifiers
These are special keywords modifying the size of a particular data-type:| Data Type | Size (in bytes) | Range |
|---|---|---|
| short int | 2 | -32,768 to 32,767 |
| unsigned short int | 2 | 0 to 65,535 |
| int | 4 | -2,147,483,648 to 2,147,483,647 |
| unsigned int | 4 | 0 to 4,294,967,295 |
| long int | 4 | -2,147,483,648 to 2,147,483,647 |
| unsigned long int | 4 | 0 to 4,294,967,295 |
| long long int | 8 | -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807 |
| unsigned long long int | 8 | 0 to 18,446,744,073,709,551,615 |
| char | 1 | -128 to 127 |
| unsigned char | 1 | 0 to 255 |
| float | 4 | 3.4E +/- 38 (7 digits) |
| double | 8 | 1.7E +/- 308 (15 digits) |
| long double | 8 | same as double |
| wchar_t | 2 | 0 to 65,535 |
1 1
2 2
3 3
c = a + b;
Add & Assign: 18
Subtract & Assign: 12
Multiply & Assign: 72
Divide & Assign: 12
int a = 10, b = 2, c = 4;
a %= b; // a = (10 % 2) = 0
a %= c; //a = (10 % 4) = 2
AND & Assign: 4
OR & Assign: 6
XOR & Assign: 15
Left-shift & Assign: 30
Right-shift & Assign: 15
6
6
7
(20 % 3) = 2
(~ 20) = -21
20 in binary (8-bit): 00010100
(~ 20): 11101011, which is -21 in 2's complement form
for negative integers.
(5 << 2) = 20
5 in binary: 101
left-shift by 2 places: 10100 ~ 20 (in decimal)
(30 >> 3) = 3
30 in binary: 11110
right-shift by 3 places: 11 ~ 3 (in decimal)
a == b: 0
a != b: 1
a < b: 1
a > b: 0
a <= c: 1
b >= c: 1
Negation: 0
AND: 0
OR: 1
1
0
1
4th element of the array (0-indexing): 4
Access via Pointer: 6
Value changed via pointer: 5
Address of b: 0x7ffdc51518d4
Direct Access: 5
Pointer Access: 5
Direct Access of Pointer: 10
Pointer Access of Pointer: 10
A *aptr = new A("Class A Instance");
delete aptr; //frees memory pointed to by aptr
int a;
cout<< sizeof(a); //prints 4
int value = (flag) ? value1 : value2
char p = (char)(65);
cout << (double)(2);
Operator Precedence
Below given is the precedence table of the various operators and their corresponding associativity:| Precedence | Operator | Description | Associativity |
|---|---|---|---|
| 1 | a++ a-- a( ) a[ ] . -> |
Post-increment/decrement Function call Array subscript Member access |
Left-to-right |
| 2 | ++a --a +a -a ! ~ (type) *a &a sizeof new delete |
Pre-increment/decrement Unary plus & minus Logical NOT & bitwise NOT Type-casting Dereferencing Address-of sizeof Dynamic Memory Allocation Memory De-allocation |
Right-to-left |
| 3 | *(a.b) *(a->b) |
Pointer to member | Left-to-right |
| 4 | a*b a/b a%b |
Multiplication, division & remainder | Left-to-right |
| 5 | a+b a-b |
Addition & subtraction | Left-to-right |
| 6 | << >> | Bitwise left-shift and right-shift | Left-to-right |
| 7 | < <= > >= |
Relational operators < and ≤ Relational operators > and ≥ |
Left-to-right |
| 8 | == != |
Relational operators = and ≠ |
Left-to-Right |
| 9 | & | Bitwise-AND | Left-to-right |
| 10 | ^ | Bitwise-XOR | Left-to-right |
| 11 | | | Bitwise-OR | Left-to-right |
| 12 | && | Logical AND | Left-to-right |
| 13 | || | Logical OR | Left-to-right |
| 14 | a?b:c = += -= *= /= %= <<= >>= &= ^= |= |
Ternary/conditional Assignment Assignment (sum, difference) Assignment (multiply, divide, modulo) Assignment (left-shift, right-shift) Assignment (AND, XOR, OR) |
Right-to-left |
| 15 | , | Comma | Left-to-right |
Character p changed to: P
Character P changed to: p
47 deg Celsius in Fahrenheit: 116.6
29 deg Celsius in Fahrenheit: 84.2
24.00
Min. notes to get a sum of 253: 6
if(condition)Here, condition after evaluation will be either true or false. if statement accepts boolean values – if the value is true then it will execute the block of statements below it otherwise not.
{
// Statements to execute if
// condition is true
}
if(condition)Flowchart:
statement1;
statement2;
// Here if the condition is true, if block
// will consider only statement1 to be inside
// its block.
I am Not in ifAs the condition present in the if statement is false. So, the block below the if statement is not executed.
if (condition)Flowchart:
{
// Executes this block if
// condition is true
}
else
{
// Executes this block if
// condition is false
}
i is greater than 15The block of code following the else statement is executed as the condition present in the if statement is false.
if (condition1)
{
// Executes when condition1 is true
if (condition2)
{
// Executes when condition2 is true
}
}
i is smaller than 15Here, a user can decide among multiple options. The if statements are executed from the top down. As soon as one of the conditions controlling the if is true, the statement associated with that if is executed, and the rest of the ladder is bypassed. If none of the conditions is true, then the final else statement will be executed.
i is smaller than 12 too
if (condition)
statement;
else if (condition)
statement;
.
.
else
statement;
i is 20Switch case statements are a substitute for long if statements that compare a variable to several integral values.
switch (n)
{
case 1: // code to be executed if n = 1;
break;
case 2: // code to be executed if n = 2;
break;
default: // code to be executed if n doesn't match any cases
}
Choice is 2
Looping Statements
Iterative Method
An iterative method to do this is to write the cout statement 10 times.Hello World
Hello World
Hello World
Hello World
Hello World
Hello World
Hello World
Hello World
Hello World
Hello World
Using Loops
In Loop, the statement needs to be written only once and the loop will be executed 10 times as shown below.for Loop
A for loop is a repetition control structure which allows us to write a loop that is executed a specific number of times. The loop enables us to perform n number of steps together in one line.for (initialization expr; test expr; update expr)In for loop, a loop variable is used to control the loop. First, initialize this loop variable to some value, then check whether this variable is less than or greater than counter value. If statement is true, then loop body is executed and loop variable gets updated. Steps are repeated till exit condition comes.
{
// body of the loop
// statements we want to execute
}
Hello World
Hello World
Hello World
Hello World
Hello World
Hello World
Hello World
Hello World
Hello World
Hello World
While Loop
While studying for loop we have seen that the number of iterations is known beforehand, i.e. the number of times the loop body is needed to be executed is known to us. while loops are used in situations where we do not know the exact number of iterations of loop beforehand. The loop execution is terminated on the basis of the test condition.initialization expression; while (test_expression)
{
// statements
update_expression; }
Hello World
Hello World
Hello World
Hello World
Hello World
do while loop
In do while loops also the loop execution is terminated on the basis of test condition. The main difference between do while loop and while loop is in do while loop the condition is tested at the end of loop body, i.e do while loop is exit controlled whereas the other two loops are entry controlled loops.initialization expression; doNote: Notice the semi - colon(";") in the end of loop.
{
// statements
update_expression; } while (test_expression);
Hello World
What about an Infinite Loop?
An infinite loop (sometimes called an endless loop ) is a piece of coding that lacks a functional exit so that it repeats indefinitely. An infinite loop occurs when a condition always evaluates to true. Usually, this is an error.This loop will run forever.
This loop will run forever.
...................
Jump Statements
Jump statements help programmers to jump directly to a point in program breaking the normal flow of execution. They provide change in program execution flow. There are 3 jump constructs in C/C++:5 found in array
1 2 3 4 5 7 8 9 10
Syntax1 | Syntax2As can be seen from the above syntax, the label can exist anywhere in the program (prior or after). Upon encountering the goto label; statement, flow jumps to the label unconditionally.
----------------------------
goto label; | label:
. | .
. | .
. | .
label: | goto label;
1 2 3 4 5
5 2 -10 5
2008101287 4195777
Size of integer in this compiler is 4
Address arr[0] is 0x7ffd636b4260
Address arr[1] is 0x7ffd636b4264
Address arr[2] is 0x7ffd636b4268
Address arr[3] is 0x7ffd636b426c
Address arr[4] is 0x7ffd636b4270
Multi-dimensional Arrays
//creates (size1 * size2) type 2-D matrixA 2-d array and a 3-d array can be visualized as:
int arr[size1][size2]
//creates (size1 * size2 * size3) type 2-D matrix
int arr[size1][size2][size3]
...
We can continue with as many dimensions as we like:
// (size1 * size2 * ... *size_n) matrix
int arr[size1][size2][size3]....[size_n]
arr[i][j];
arr[i][j][k];
C-style (character arrays and literals)
C-style strings are defined using character arrays. There is an extra character called the null (\0) character appended to the character array to mark it's end.char str_name[size];
char str[size];Below is the memory representation of a string "Geeks".
char str[] = "Geeks";
char str[5] = "Geeks";
char str[] = {'G','e','e','k','s'};
Input: Hello
Output: Hello
HELLO
destinationsource
-100 <0 indicating str1 appears before str2
1 >0 indicating str1 appears after str3
1 >0 indicating str2 appears after str3
Source: Hello World
Destination: Hello World
First occurrence of string 'for'
in 'GeeksforGeeks' is 'forGeeks'
String Class in C++ STL
| C-style character array | C++ string class |
|---|---|
| Array of characters terminated by null (\0) | Class object instance storing stream of characters |
| Allocated Statically (can't be modified in run-time) | Allocated Dynamically (modifiable at run-time) |
| Vulnerable to array decay | Class-based implementation evades such vulnerabilities |
| Limited inbuilt functions for manipulation | Rich inbuilt function support for manipulation |
string str_name;
Input: Hello
Output: Hello
5
// Both of the below methods works fine:
Method 1:
string str = "This is a sample string"; // This is correct
Method 2:
string str;
str = "This is a sample string"; // This is also correct
GeeksforGeeks
Print 1st character: G
s
Length of String: 13
String is empty
Hello and Good Day to Everyone
abcd
abc
5
String 'abc' not found
for
forGeeks
12
+ 4 5Output
* 2 3
Q
- 5 4
9
6
4.16667
string kayak is a palindrome
string kappa is not a palindrome
11101
< return-type > < function-name > (< set-of-arguments >) {
//block of statements
}
As an example:Maximum of a & b is: 20
Prototype Declaration & Definition
Sometimes, we just want to declare the existence of a function and provide the implementation afterwards. We can do so by using the prototype-declaration scheme, the syntax of which is given below:< return-type > < function-name > (< set-of-arguments >);As an example:
Formal & Actual Parameters
The parameters passed to function are called actual parameters. For example, in the first program 10 and 20 are actual parameters. The parameters received by function are called formal parameters. For example, in the above program x and y are formal parameters.Pass by value & Pass by Reference
There are two types of passing arguments to functions. The arguments declared within the function (formal parameter variables) have function block scope only. Hence, any manipulation done on them has no effect on the actual variables with which the function was called. This will be clear with the following Pass by value example:a: 5, b: 6As we can see, the values inside of main don't get swapped. This is because they were passed by value. Hence, any change done inside the function isn't reflected in the main() part. This is because in pass-by-value, the value and not the actual memory location gets copied to the formal parameters in the function.
int swap(int &a, int &b) { ... }
//add & before the parameters (call-by-reference)
...
int a = 5, b = 6;
swap(a, b); //calling the function remains the same
a: 6, b: 5So, the elements get swapped in real.
Inline Functions
Inline functions are an improvement provided by C++ to reduce the overhead caused in executing a function call. A function call statement is a jump statement that instructs the program counter to switch to a different address for execution. In a function call, a lot of work that the OS needs to be done such as storing the current address of execution (to return back to), along with other registers. Also, allocation and de-allocation (upon exit) of variables local to the functions are done. This can greatly hamper performance if a function is called repeatedly in a program. e.g. frequently called utility functions such as min(), max(), or in case of recursive functions such as factorial().6
8
cout << (5 > 6) ? 5 : 6 << endl;If there are multiple calls to max_int function, usage of inline can greatly improve performance. However, there is an added downside of increased compilation code size, because of inline-expansion. Thus, it is advised to make only those functions inline which are short & frequently used.
cout << (8 > 7) ? 8 : 7 << endl;
Default Arguments
A Default Argument is a default value for a function argument. In case the user forgets to provide the parameter, the default value for that variable would be used. As an example:11
5
int add(int y=10, int x); //not allowedas a call to a function like add( , 3) is not allowed in C++. Rather add(3) is valid. So, all default params should follow the non-default ones.
int add(int x, int y=10); //allowed
Function Overloading
Function overloading allows us to create functions with different names, as long as they have different parameters. As an example:11
Hello World
Function Pointers
Functions are an executable block of code which is placed at a certain address when a program is loaded into memory. e.g. If we execute the code below:0x002717f0
< return-type > (* < function-name >)(< argument-list >);Example:
11
Hello World
0 1 2 3 4 5 6 7 8 9
9 8 7 6 5 4 3 2 1 0
Variable Arguments
One might have seen functions such as printf, scanf which are capable of printing/scanning any number of input arguments provided. This is achieved by using variable arguments. The advantage of having a variable argument feature in C++ is to have functions which can operate on any number of arguments and produce the result. e.g. Suppose we want a function that can take the average of any number of integers passed:6.95312e-310
4.16905e-310
datatype *var_name;
int *ptr; //ptr can point to an address which holds int data
Value at ptr = 0x7ffdcf42ad9c
Value at var = 20
Value at *ptr = 20
References in C++
C++ References is a new language construct which was introduced to reduce the dependency over pointers for doing indirect memory access. Usage of pointers requires caution as the programmer needs to manually deallocate them to avoid memory leaks. A reference is an alternative name for a memory location. References are useful in following situations -3 2
Types of Function Call (References v/s Pointers)
There are 3 ways to pass C++ arguments to a function:address of n1 in main(): 0x7ffec6732e4c
address of n1 in square1(): 0x7ffec6732e2c
Square of n1: 64
No change in n1: 8
address of n2 in main(): 0x7ffec6732e50
address of n2 in square2(): 0x7ffec6732e50
Square of n2: 64
Change reflected in n2: 64
address of n3 in main(): 0x7ffec6732e54
address of n3 in square3(): 0x7ffec6732e54
Square of n3: 64
Change reflected in n3: 64
Array Name as Pointers
An array name contains the address of first element of the array which acts like constant pointer. It means, the address stored in array name can't be changed.Elements of the array are: 5 10 20
Pointers and String literals
String literals are arrays containing null-terminated character sequences. String literals are arrays of type character plus terminating null-character, with each of the elements being of type const char (as characters of string can't be modified).const char * ptr = "geek";
This declares an array with the literal representation for "geek", and then a pointer to its first element is assigned to ptr. If we imagine that "geek" is stored at the memory locations that start at address 1800, we can represent the previous declaration as:char x = *(ptr+3);
char y = ptr[3];
Here, both x and y contain k stored at 1803 (1800+3).Pointers to pointers
In C++, we can create a pointer to a pointer that in turn may point to data or other pointer. The syntax simply requires the unary operator (*) for each level of indirection while declaring the pointer.char a;
char *b;
char ** c;
a = ’g’;
b = &a;
c = &b;
Here b points to a char that stores ‘g’ and c points to the pointer b.Void Pointers
This is a special type of pointer available in C++ which represents absence of type. void pointers are pointers that point to a value that has no type (and thus also an undetermined length and undetermined dereferencing properties).*data points to a char
The new value of c is: y
*data points to an int
The new value of i is: 11
Invalid pointers
A pointer should point to a valid address but not necessarily to valid elements (like for arrays). These are called invalid pointers. Uninitialized pointers are also invalid pointers.int *ptr1;
int arr[10];
int *ptr2 = arr+20;
Here, ptr1 is uninitialized so it becomes an invalid pointer and ptr2 is out of bounds of arr so it also becomes an invalid pointer.NULL Pointers
Null pointer is a pointer which point nowhere and not just an invalid address.int *ptr1 = 0;
int *ptr2 = NULL;
ptr = (cast-type*) malloc(byte-size)
For Example:
ptr = (int*) malloc(100 * sizeof(int));
Since the size of int is 4 bytes,
this statement will allocate 400 bytes of memory.
And, the pointer ptr holds the address of the
first byte in the allocated memory.
Enter number of elements: 5
Memory successfully allocated using malloc
The elements of the array are: 1, 2, 3, 4, 5,
ptr = (cast-type*)calloc(n, element-size);
For Example:
ptr = (float*) calloc(25, sizeof(float));
This statement allocates contiguous space in memory for
25 elements each with the size of float.
Enter number of elements: 5
Memory successfully allocated using calloc
The elements of the array are: 1, 2, 3, 4, 5,
free(ptr);
Enter number of elements: 5
Memory successfully allocated using malloc
Malloc Memory successfully freed.
Memory successfully allocated using calloc
Calloc Memory successfully freed.
ptr = realloc(ptr, newSize);
where ptr is reallocated with new size 'newSize'.
Enter number of elements: 5
Memory successfully allocated using calloc.
The elements of the array are: 1, 2, 3, 4, 5,
Enter the new size of the array: 10
Memory successfully re-allocated using realloc.
The elements of the array are: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10,
<pointer-variable> = new <data-type>As an example:
delete <pointer-variable>As an example:
Value of a: 6
Value of b: 5
1 2 3 4
5 6 7 8
9 10 11 12
VOID Pointers
A void pointer is a pointer that doesn't have any type and thus can point to any data-type by explicit casting. Since the data-type this pointer refers to isn't defined upon declaration, we can't dereference a void pointer.prog.cpp: In function 'int main()':All the assignment statements are valid because a void pointer can be made to point to any data-type. However, the above code doesn't compile because of the line:
prog.cpp:17:14: error: 'void*' is not a pointer-to-object type
cout << *p << endl;
^
NULL Pointers
A pointer declared a value always contains garbage value, thus pointing to a random location in memory. To signify a pointer as not pointing to any meaningful variable, we use the NULL Macro. NULL is a Macro defined in standard library, and it's value is generally implementation specific, but most compilers set it to value: 0. Thus, assigning NULL to a pointer, and putting it in an if-statement generates boolean-false (because of 0):0
Pointer is NULL
prog.cpp: In function 'int main()':Since NULL is 0, it may mean int as well as int*, causing ambiguity. To fix this, C++ introduced nullptr pointer-literal keyword. In modern C++ usage, thus we set a pointer to nullptr instead of NULL, when we declare a pointer pointing to nothing. Same above code with the call: fun(nullptr) will not generated any errors as ambiguity is removed.
prog.cpp:13:10: error: call of overloaded 'fun(NULL)' is ambiguous
fun(NULL); //ambiguity issue
^
prog.cpp:4:6: note: candidate: void fun(int)
void fun(int x) { cout << "Integer Call: " << x << endl; }
^
prog.cpp:5:6: note: candidate: void fun(int*)
void fun(int *x) { cout << "Pointer Call: " << x << endl; }
^
struct <structure-name> {
//data members
}
Usage example of structure:Name: David
Age: 24
Salary: 2.5
Is remote?: 1
Pointer Access: David
24
2 2
3 3
2
sunday: 1,
monday: 2,
tuesday: 5,
wednesday: 6,
thursday: 10,
friday: 11,
saturday: 12
namespace < namespace-name > {
//declare variables
//declare classes, structures, enums, unions
//declare functions
}
Example
Suppose we have 2 header files A.h and B.h containing the same-named function compute():Output:As we can see, by using namespaces and referring to the appropriate function (using :: Scope Resolution Operator, we can avoid name-collisions.
30
11
ID: GFG1, Name: Robert, Year: 3, CGPA: 8.67
ID: GFG2, Name: Chris, Year: 2, CGPA: 9.13
ID: GFG3, Name: Mark, Year: 4, CGPA: 8.43
1 2 3 4 5 6
1 2 3 4 5 6
bool -> char -> short int -> int ->
unsigned int -> long -> unsigned ->
long long -> float -> double -> long double
x = 107
y = a
z = 108
(type) expressionwhere type indicates the data type to which the final result is converted.
Sum = 2
3
I'm in Child
Old roll number: 3
New roll number: 5